import { parentPort, workerData } from 'worker_threads';
import generateGradeReport from '../helpers/grades_report_pdf_bulider.js';
import { uploadFileToPinata } from '../helpers/pinata_ipfs.js';
import path from 'path';
import crypto from 'crypto';
import fs from 'fs';
import { fileURLToPath } from 'url';

// 添加ES模块的__dirname替代方案
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function processStudentReport() {
    try {
        //console.log("workerData",workerData)
        const { student, semester_name, formattedRecords, summary_id } = workerData;

        console.log(`开始处理学生 ${student.dataValues.user_id} 的成绩报告...`);
        
        const pdfFileName = `${student.dataValues.name}-${student.dataValues.personnel_id}.pdf`;
        const pdfPath = await generateGradeReport(
            formattedRecords,
            {
                name: student.dataValues.name,
                personnel_id: student.dataValues.personnel_id,
                ethereum_address: student.dataValues.ethereum_address
            },
            path.join(__dirname, '../assets/reports', pdfFileName)
        );

        const pdfFile = fs.readFileSync(pdfPath);
        const ipfsHash = await uploadFileToPinata(pdfFile, pdfFileName);
        
        // 生成最终数据哈希
        const finalHash = crypto.createHash('sha256')
            .update(JSON.stringify(formattedRecords))
            .digest('hex');

        parentPort.postMessage({
            summary_id,
            status: 'completed',
            pdf_path: `reports/${pdfFileName}`,
            ipfsHash,
            data_hash: finalHash
        });
    } catch (error) {
        parentPort.postMessage({
            summary_id: workerData.summary_id,
            status: 'failed',
            error: error.message
        });
    }
}

processStudentReport();